let isSocketClose = false; // 是否关闭socket
let reconnectCount = 5; // 重连次数
// let heartbeatInterval = ""; // 心跳定时器
let socketTask = null; // websocket对象

let againTimer = null; //断线重连定时器


let url = 'wss://dcs.devonline.cn/dcs';

/**
 * sockeUrl：websocet的地址
 * onReceive：消息监听的回调
 * */
const init = (data, onReceive) => {
	function jsonToUrlParam(json) {
		return Object.keys(json).map(key => key + '=' + json[key]).join('&');
	}
	url += `?${jsonToUrlParam(data)}`
	isSocketClose = false;
	//判断是否有websocet对象，有的话清空
	if (socketTask) {
		socketTask.close();
		socketTask = null;
		// clearInterval(heartbeatInterval);
	} 
	// 连接
	socketTask = uni.connectSocket({
		url: url,
		success(data) {
			console.log("websocket连接成功",url);
			clearInterval(againTimer) //断线重连定时器
		},
		fail: (err) => {
			console.log("报错", err);
		}
	});
	// 连接打开
	socketTask.onOpen((res) => {
   console.log('WebSocket打开')
		
		socketTask.send({
			data: `{"protocol":"json","version":1}${String.fromCharCode(0x1e)}`
		});
		
		clearInterval(againTimer) //断线重连定时器


		// heartbeatInterval && clearInterval(heartbeatInterval);

		// // 30秒发送一次心跳
		// heartbeatInterval = setInterval(() => {
		// 	sendMsg('PING')
		// }, 1000 * 30)
	})
	// 监听连接失败
	socketTask.onError((err) => {
		//停止发送心跳
		// clearInterval(heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!isSocketClose) {
			reconnect(url)
		}
	})

	// // 监听连接关闭 -
	socketTask.onClose((e) => {
		console.log('WebSocket连接关闭！');
		// clearInterval(heartbeatInterval)
		if (!isSocketClose) {
			reconnect(url)
		}
	})

	// 监听收到信息
	socketTask.onMessage((res) => {
		uni.hideLoading()
		console.log(res, 'res监听收到信息')
		let serverData = res.data
		serverData && onReceive(serverData);
	});
}

const reconnect = (url) => {
	clearInterval(againTimer) //断线重连定时器
	// clearInterval(heartbeatInterval);
	socketTask && socketTask.close(); // 确保已经关闭后再重新打开
	socketTask = null;
	let num=0
	// 连接  重新调用创建websocet方法
	againTimer = setInterval(() => {
		if(num>reconnectCount) return	clearInterval(againTimer) 
		init(url)
		num++
	}, 1000 * 5)


}

const sendMsg = (msg) => { //向后端发送命令
	msg = JSON.stringify(msg)
	
	try {
		//通过 WebSocket 连接发送数据
		socketTask.send({
			Send: msg
		});
		console.log('发送',msg)
	} catch (e) {
		if (isSocketClose) {
			return
		} else {
			reconnect(url)
		}

	}
}
// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】beforeDestroy() {websocetObj.stop();}
const stop = () => {
	isSocketClose = true
	// clearInterval(heartbeatInterval);
	clearInterval(againTimer) //断线重连定时器
	socketTask.close(); // 确保已经关闭后再重新打开
	socketTask = null;
}


const $debounce = function(fn, wait) {
	let timer = null;
	return function() {
		if (timer !== null) {
			clearTimeout(timer);
		}
		timer = setTimeout(fn, wait);
	}
}

export const websocetObj = {
	init,
	socketTask,
	stop,
	sendMsg
};
